from django.db.models.functions import Coalesce
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.http import JsonResponse
from django.db.models import Count, Q,Subquery,OuterRef
from django.utils import timezone
from datetime import datetime, timedelta
import random
import json
from .models import *

from .forms import *


def index(request):
    if not request.user.is_authenticated:
        return render(request, 'main/index.html')

    # 获取用户偏好
    try:
        user_pref = UserPreference.objects.get(user=request.user)
        preferred_categories = user_pref.preferred_categories.all()
    except UserPreference.DoesNotExist:
        user_pref = None
        preferred_categories = []

    # 获取今天的记录
    today = timezone.now().date()
    try:
        today_record = DailyFoodRecord.objects.get(user=request.user, date=today)
    except DailyFoodRecord.DoesNotExist:
        today_record = None

    # 随机推荐逻辑
    all_foods = FoodItem.objects.all()

    # 如果有偏好，优先推荐偏好类别
    if preferred_categories:
        preferred_foods = all_foods.filter(category__in=preferred_categories)
        if preferred_foods:
            all_foods = preferred_foods

    # 排除不喜欢的食物
    if user_pref:
        disliked_foods = user_pref.disliked_foods.all()
        all_foods = all_foods.exclude(id__in=disliked_foods)

    # 随机选择
    breakfast_rec = random.choice(list(all_foods)) if all_foods else None
    lunch_rec = random.choice(list(all_foods)) if all_foods else None
    dinner_rec = random.choice(list(all_foods)) if all_foods else None

    # 本周统计（简化：近7天记录数、最常吃类别）
    week_start = today - timedelta(days=6)
    week_records = DailyFoodRecord.objects.filter(user=request.user, date__gte=week_start, date__lte=today)
    week_records_count = week_records.values('date').distinct().count()
    top_category = None
    if week_records.exists():
        category_counts = {}
        for rec in week_records:
            if rec.breakfast:
                category_counts[rec.breakfast.category.name] = category_counts.get(rec.breakfast.category.name, 0) + 1
            if rec.lunch:
                category_counts[rec.lunch.category.name] = category_counts.get(rec.lunch.category.name, 0) + 1
            if rec.dinner:
                category_counts[rec.dinner.category.name] = category_counts.get(rec.dinner.category.name, 0) + 1
            for snack in rec.snacks.all():
                category_counts[snack.category.name] = category_counts.get(snack.category.name, 0) + 1
        if category_counts:
            top_category = sorted(category_counts.items(), key=lambda kv: kv[1], reverse=True)[0][0]

    # 标签层级：父级及其子级
    parent_tags = Tag.objects.filter(parent__isnull=True).order_by('name').prefetch_related('children')

    context = {
        'today_record': today_record,
        'breakfast_rec': breakfast_rec,
        'lunch_rec': lunch_rec,
        'dinner_rec': dinner_rec,
        'today': today,
        'all_foods': FoodItem.objects.all(),
        'week_records_count': week_records_count,
        'top_category': top_category,
        'parent_tags': parent_tags,
    }
    return render(request, 'main/index.html', context)


@login_required
def tag_list(request):
    """标签列表"""
    tags = Tag.objects.annotate(
        food_count=Count('food_items', distinct=True),
        record_count=Count('daily_records', distinct=True)
    ).order_by('name')

    # 搜索功能
    search_query = request.GET.get('search', '')
    if search_query:
        tags = tags.filter(name__icontains=search_query)

    context = {
        'tags': tags,
        'search_query': search_query,
    }
    return render(request, 'main/tag_list.html', context)


@login_required
def tag_create(request):
    """创建新标签"""
    if request.method == 'POST':
        form = TagForm(request.POST)
        if form.is_valid():
            tag = form.save(commit=False)
            tag.created_by = request.user
            tag.save()
            messages.success(request, f'标签 "{tag.name}" 创建成功!')
            return redirect('main:tag_list')
    else:
        form = TagForm()

    context = {'form': form}
    return render(request, 'main/tag_form.html', context)


@login_required
def tag_edit(request, tag_id):
    """编辑标签"""
    tag = get_object_or_404(Tag, id=tag_id)

    # 检查权限（只有创建者或超级用户可以编辑）
    if not request.user.is_superuser and tag.created_by != request.user:
        messages.error(request, '您没有权限编辑此标签')
        return redirect('main:tag_list')

    if request.method == 'POST':
        form = TagForm(request.POST, instance=tag)
        if form.is_valid():
            form.save()
            messages.success(request, f'标签 "{tag.name}" 更新成功!')
            return redirect('main:tag_list')
    else:
        form = TagForm(instance=tag)

    context = {'form': form, 'tag': tag}
    return render(request, 'main/tag_form.html', context)


@login_required
def tag_delete(request, tag_id):
    """删除标签"""
    tag = get_object_or_404(Tag, id=tag_id)

    # 检查权限
    if not request.user.is_superuser and tag.created_by != request.user:
        messages.error(request, '您没有权限删除此标签')
        return redirect('main:tag_list')

    if request.method == 'POST':
        tag_name = tag.name
        tag.delete()
        messages.success(request, f'标签 "{tag_name}" 已删除!')
        return redirect('main:tag_list')

    context = {'tag': tag}
    return render(request, 'main/tag_confirm_delete.html', context)


@login_required
def tag_detail(request, tag_id):
    """标签详情页"""
    tag = get_object_or_404(Tag, id=tag_id)

    # 获取使用此标签的食物
    foods_with_tag = tag.food_items.all()

    # 获取使用此标签的每日记录
    records_with_tag = tag.daily_records.filter(user=request.user)

    context = {
        'tag': tag,
        'foods_with_tag': foods_with_tag,
        'records_with_tag': records_with_tag,
    }
    return render(request, 'main/tag_detail.html', context)

@login_required
def save_daily_record(request):
    if request.method == 'POST':
        date_str = request.POST.get('date')
        date = datetime.strptime(date_str, '%Y-%m-%d').date() if date_str else timezone.now().date()

        breakfast_id = request.POST.get('breakfast')
        lunch_id = request.POST.get('lunch')
        dinner_id = request.POST.get('dinner')
        snack_ids = request.POST.getlist('snacks')
        notes = request.POST.get('notes', '')

        # 获取或创建记录
        record, created = DailyFoodRecord.objects.get_or_create(
            user=request.user,
            date=date,
            defaults={
                'breakfast_id': breakfast_id if breakfast_id else None,
                'lunch_id': lunch_id if lunch_id else None,
                'dinner_id': dinner_id if dinner_id else None,
                'notes': notes
            }
        )

        if not created:
            record.breakfast_id = breakfast_id if breakfast_id else None
            record.lunch_id = lunch_id if lunch_id else None
            record.dinner_id = dinner_id if dinner_id else None
            record.notes = notes
            record.save()

        # 处理零食
        if snack_ids:
            record.snacks.set(FoodItem.objects.filter(id__in=snack_ids))

        messages.success(request, '饮食记录已保存!')
        return redirect('main:index')

    return redirect('main:index')


@login_required
def history(request):
    records = DailyFoodRecord.objects.filter(user=request.user).order_by('-date')

    # 日期筛选
    date_from = request.GET.get('date_from')
    date_to = request.GET.get('date_to')

    if date_from:
        records = records.filter(date__gte=date_from)
    if date_to:
        records = records.filter(date__lte=date_to)

    context = {
        'records': records,
        'date_from': date_from,
        'date_to': date_to,
    }
    return render(request, 'main/history.html', context)


def get_user_tags_optimized(user):
    """用户标签统计"""
    # 子查询：统计通过食物使用的标签次数
    food_usage_subquery = Tag.objects.filter(
        id=OuterRef('id')
    ).filter(
        Q(food_items__breakfast_records__user=user) |
        Q(food_items__lunch_records__user=user) |
        Q(food_items__dinner_records__user=user) |
        Q(food_items__snack_records__user=user)
    ).annotate(
        count=Count('id', distinct=True)
    ).values('count')[:1]

    # 子查询：统计直接用于记录的标签次数
    record_usage_subquery = Tag.objects.filter(
        id=OuterRef('id')
    ).filter(
        daily_records__user=user
    ).annotate(
        count=Count('id', distinct=True)
    ).values('count')[:1]

    # 主查询：合并两个使用次数
    user_tags = Tag.objects.annotate(
        food_usage_count=Coalesce(Subquery(food_usage_subquery), 0),
        record_usage_count=Coalesce(Subquery(record_usage_subquery), 0),
        total_usage_count=Coalesce(Subquery(food_usage_subquery), 0) +
                          Coalesce(Subquery(record_usage_subquery), 0)
    ).filter(
        total_usage_count__gt=0
    ).order_by('-total_usage_count')[:10]

    # 为每个标签对象添加usage_count属性以保持模板兼容性
    for tag in user_tags:
        tag.usage_count = tag.total_usage_count

    return user_tags

@login_required
def preferences(request):
    user_pref, created = UserPreference.objects.get_or_create(user=request.user)

    if request.method == 'POST':
        # ... 原有的POST处理代码保持不变 ...
        preferred_category_ids = request.POST.getlist('preferred_categories')
        disliked_food_ids = request.POST.getlist('disliked_foods')
        preferred_tag_ids = request.POST.getlist('preferred_tags')
        dietary_restrictions = request.POST.get('dietary_restrictions', '')

        user_pref.preferred_categories.set(FoodCategory.objects.filter(id__in=preferred_category_ids))
        user_pref.disliked_foods.set(FoodItem.objects.filter(id__in=disliked_food_ids))
        user_pref.preferred_tags.set(Tag.objects.filter(id__in=preferred_tag_ids))
        user_pref.dietary_restrictions = dietary_restrictions
        user_pref.save()

        messages.success(request, '偏好设置已更新!')
        return redirect('preferences')
        # 简化版本：分别查询不同餐次，然后在Python中合并统计
    user_records = DailyFoodRecord.objects.filter(user=request.user)

    # 收集所有食物ID
    food_ids = []
    for record in user_records:
        if record.breakfast:
            food_ids.append(record.breakfast.id)
        if record.lunch:
            food_ids.append(record.lunch.id)
        if record.dinner:
            food_ids.append(record.dinner.id)
        food_ids.extend(record.snacks.values_list('id', flat=True))

    user_tags = get_user_tags_optimized(request.user)

    # 统计食物出现次数
    from collections import Counter
    food_counter = Counter(food_ids)

    # 获取最常吃的食物
    top_food_ids = [food_id for food_id, count in food_counter.most_common(10)]
    food_stats = FoodItem.objects.filter(id__in=top_food_ids)

    # 为每个食物添加计数
    for food in food_stats:
        food.total_count = food_counter[food.id]

    # 按计数排序
    food_stats = sorted(food_stats, key=lambda x: x.total_count, reverse=True)

    # 统计类别出现次数
    category_counter = Counter()
    for food in FoodItem.objects.filter(id__in=food_ids):
        category_counter[food.category.id] += food_counter[food.id]

    # 获取最常吃的类别
    top_category_ids = [cat_id for cat_id, count in category_counter.most_common(5)]
    category_stats = FoodCategory.objects.filter(id__in=top_category_ids)

    # 为每个类别添加计数
    for category in category_stats:
        category.total_count = category_counter[category.id]

    # 按计数排序
    category_stats = sorted(category_stats, key=lambda x: x.total_count, reverse=True)

    # 获取其他统计数据
    total_records = user_records.count()

    # 最近30天的记录
    from datetime import timedelta
    thirty_days_ago = timezone.now().date() - timedelta(days=30)
    recent_records = user_records.filter(date__gte=thirty_days_ago).count()

    context = {
        'user_pref': user_pref,
        'all_categories': FoodCategory.objects.all(),
        'all_foods': FoodItem.objects.all(),
        'all_tage':Tag.objects.filter(parent__isnull=False),
        'user_tags':user_tags,
        'category_stats': category_stats,
        'food_stats': food_stats,
        'total_records': total_records,
        'recent_records': recent_records,
    }
    return render(request, 'main/preferences.html', context)
@login_required
def get_tags_json(request):
    """返回所有标签的JSON数据，用于前端选择"""
    tags = Tag.objects.all().values('id', 'name', 'color')
    return JsonResponse(list(tags), safe=False)

@login_required
def food_detail_json(request, food_id):
    """返回食物详情的JSON数据"""
    try:
        food = FoodItem.objects.get(id=food_id)
        tags = [tag.name for tag in food.tags.all()]
        data = {
            'name': food.name,
            'category': food.category.name,
            'description': food.description or '暂无描述',
            'tags': ', '.join(tags) if tags else '无标签'
        }
        return JsonResponse(data)
    except FoodItem.DoesNotExist:
        return JsonResponse({'error': '食物不存在'}, status=404)

@login_required
def food_library(request):
    """食物库页面 - 支持分类筛选和搜索"""
    categories = FoodCategory.objects.all()
    category_id = request.GET.get('category')
    search_keyword = request.GET.get('search', '').strip()

    # 获取食物列表
    foods = FoodItem.objects.select_related('category').prefetch_related('tags').all()

    # 分类筛选
    if category_id:
        foods = foods.filter(category_id=category_id)

    # 搜索功能
    if search_keyword:
        foods = search_food(request)

    context = {
        'foods': foods,
        'categories': categories,
        'selected_category': category_id,
        'search_keyword': search_keyword,
    }
    return render(request, 'main/food_library.html', context)


def search_food(request):
    """搜索食物 - 支持中文、全拼、简拼"""
    kw = request.GET.get('kw', '').strip()
    qs = FoodItem.objects.select_related('category').prefetch_related('tags')
    if kw:
        qs = qs.filter(
            Q(name__icontains=kw)           |   # 中文搜索
            Q(name_pinyin__icontains=kw)    |   # 全拼搜索
            Q(name_py_abbr__icontains=kw)       # 简拼搜索
        )
    return qs

@login_required
def food_search_api(request):
    """食物搜索API接口 - 用于实时搜索建议"""
    kw = request.GET.get('q', '').strip()
    results = []
    
    if kw and len(kw) >= 1:  # 至少输入1个字符
        foods = FoodItem.objects.filter(
            Q(name__icontains=kw) |
            Q(name_pinyin__icontains=kw) |
            Q(name_py_abbr__icontains=kw)
        ).select_related('category')[:10]  # 限制返回10个结果
        
        for food in foods:
            results.append({
                'id': food.id,
                'name': food.name,
                'category': food.category.name,
                'description': food.description[:50] + '...' if len(food.description) > 50 else food.description,
            })
    
    return JsonResponse({
        'results': results,
        'count': len(results)
    })

@login_required
def add_food(request):
    if request.method == 'POST':
        form = FoodItemForm(request.POST)
        if form.is_valid():
            food_item = form.save(commit=False)
            food_item.created_by = request.user
            food_item.save()
            form.save_m2m()  # 保存多对多关系（标签）
            messages.success(request, f'食物 "{food_item.name}" 添加成功!')
            return redirect('main:food_library')
    else:
        form = FoodItemForm()

    context = {'form': form}
    return render(request, 'main/add_food.html', context)


# ========== 做菜指南相关视图 ==========

@login_required
def caipu_list(request):
    """菜谱列表页"""
    # 获取所有菜谱
    caipus = Caipu.objects.all().order_by('-id')
    
    # 搜索功能
    search_query = request.GET.get('search', '')
    if search_query:
        caipus = caipus.filter(title__icontains=search_query)
    
    # 分页功能
    from django.core.paginator import Paginator
    paginator = Paginator(caipus, 9)  # 每页10条
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    context = {
        'search_query': search_query,
        'page_obj': page_obj
    }
    return render(request, 'main/caipu_list.html', context)


def caipu_detail(request, caipu_id):
    """菜谱详情页"""
    # 获取菜谱详情
    caipu = get_object_or_404(Caipu, pk=caipu_id)
    
    # 使用模型中定义的方法处理数据
    steps = caipu.get_steps_list()
    images = caipu.get_steppic_list()
    thumb_images = caipu.get_images_list()
    ingredients = caipu.get_ingredients_list()
    
    # 找到对应的步骤图片匹配关系
    steps_with_images = []
    for idx, step in enumerate(steps, 1):
        steps_with_images.append({
            'step': step,
            'image': images[idx - 1] if idx <= len(images) else None
        })
    pages=request.GET.get('page')
    context = {
        'caipu': caipu,
        'ingredients': ingredients,
        'steps_with_images': steps_with_images,
        'main_image': thumb_images[0] if thumb_images else None,
        'thumb_images': thumb_images,
        'back_page':pages[0] if pages else '1'
    }
    print(pages[0] if pages else '1')
    return render(request, 'main/caipu_detail.html', context)


@login_required
def recipe_list(request):
    """做菜指南列表"""
    recipes = Recipe.objects.all().prefetch_related('category', 'tags', 'created_by')
    
    # 搜索功能
    search_query = request.GET.get('search', '')
    if search_query:
        recipes = recipes.filter(name__icontains=search_query)
    
    # 分类筛选
    category_id = request.GET.get('category')
    if category_id:
        recipes = recipes.filter(category_id=category_id)
    
    # 难度筛选
    difficulty = request.GET.get('difficulty')
    if difficulty:
        recipes = recipes.filter(difficulty=difficulty)
    
    context = {
        'recipes': recipes,
        'search_query': search_query,
        'categories': FoodCategory.objects.all(),
        'difficulty_choices': Recipe.DIFFICULTY_CHOICES,
        'selected_category': category_id,
        'selected_difficulty': difficulty,
    }
    return render(request, 'main/recipe_list.html', context)


@login_required
def recipe_detail(request, recipe_id):
    """做菜指南详情"""
    recipe = get_object_or_404(Recipe, id=recipe_id)
    ingredients = recipe.ingredients.all()
    steps = recipe.steps.all()
    
    context = {
        'recipe': recipe,
        'ingredients': ingredients,
        'steps': steps,
    }
    return render(request, 'main/recipe_detail.html', context)


@login_required
def recipe_create(request):
    """创建做菜指南"""
    if request.method == 'POST':
        form = RecipeForm(request.POST, request.FILES)
        ingredient_formset = RecipeIngredientFormSet(request.POST)
        step_formset = RecipeStepFormSet(request.POST, request.FILES)
        
        if form.is_valid() and ingredient_formset.is_valid() and step_formset.is_valid():
            recipe = form.save(commit=False)
            recipe.created_by = request.user
            recipe.save()
            form.save_m2m()  # 保存多对多关系
            
            # 保存食材和步骤
            ingredient_formset.instance = recipe
            ingredient_formset.save()
            
            step_formset.instance = recipe
            step_formset.save()
            
            messages.success(request, f'做菜指南 "{recipe.name}" 创建成功!')
            return redirect('main:recipe_detail', recipe_id=recipe.id)
    else:
        form = RecipeForm()
        ingredient_formset = RecipeIngredientFormSet()
        step_formset = RecipeStepFormSet()
    
    context = {
        'form': form,
        'ingredient_formset': ingredient_formset,
        'step_formset': step_formset,
    }
    return render(request, 'main/recipe_form.html', context)


@login_required
def recipe_edit(request, recipe_id):
    """编辑做菜指南"""
    recipe = get_object_or_404(Recipe, id=recipe_id)
    
    # 检查权限（只有创建者或超级用户可以编辑）
    if not request.user.is_superuser and recipe.created_by != request.user:
        messages.error(request, '您没有权限编辑此做菜指南')
        return redirect('main:recipe_list')
    
    if request.method == 'POST':
        form = RecipeForm(request.POST, request.FILES, instance=recipe)
        ingredient_formset = RecipeIngredientFormSet(request.POST, instance=recipe)
        step_formset = RecipeStepFormSet(request.POST, request.FILES, instance=recipe)
        
        if form.is_valid() and ingredient_formset.is_valid() and step_formset.is_valid():
            form.save()
            ingredient_formset.save()
            step_formset.save()
            
            messages.success(request, f'做菜指南 "{recipe.name}" 更新成功!')
            return redirect('main:recipe_detail', recipe_id=recipe.id)
    else:
        form = RecipeForm(instance=recipe)
        ingredient_formset = RecipeIngredientFormSet(instance=recipe)
        step_formset = RecipeStepFormSet(instance=recipe)
    
    context = {
        'form': form,
        'ingredient_formset': ingredient_formset,
        'step_formset': step_formset,
        'recipe': recipe,
    }
    return render(request, 'main/recipe_form.html', context)


@login_required
def recipe_delete(request, recipe_id):
    """删除做菜指南"""
    recipe = get_object_or_404(Recipe, id=recipe_id)
    
    # 检查权限
    if not request.user.is_superuser and recipe.created_by != request.user:
        messages.error(request, '您没有权限删除此做菜指南')
        return redirect('main:recipe_list')
    
    if request.method == 'POST':
        recipe_name = recipe.name
        recipe.delete()
        messages.success(request, f'做菜指南 "{recipe_name}" 已删除!')
        return redirect('main:recipe_list')
    
    context = {'recipe': recipe}
    return render(request, 'main/recipe_confirm_delete.html', context)